package com.imooc.mybatisplusappdemo.controller;

import com.imooc.mybatisplusappdemo.dto.LoginDto;
import com.imooc.mybatisplusappdemo.service.AccountService;
import com.imooc.mybatisplusappdemo.service.ResourceService;
import com.imooc.mybatisplusappdemo.vo.ResourceVO;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("auth")
public class LoginController {

  @Autowired
  private AccountService accountService;

  @Autowired
  private ResourceService resourceService;

  /**
   * 用户登录
   * @param username
   * @param password
   * @return
   */
  @PostMapping("login")
  public String login(String username, String password, HttpSession session
                      , RedirectAttributes attributes
                      , Model model){

    LoginDto loginDto = accountService.login(username, password);

    if (null == loginDto.getError()) {
      session.setAttribute("account", loginDto.getAccount());
      List<ResourceVO> resourceVOS = resourceService
          .listResourceByRoleId(loginDto.getAccount().getRoleId());
      model.addAttribute("resources", resourceVOS);
    } else {
      attributes.addFlashAttribute("error", loginDto.getError());
    }

    return loginDto.getPath();
  }

  @GetMapping("logout")
  public String logout(HttpSession session){
    session.invalidate();
    return "redirect:/";
  }


}
